//
//  DataManager.m
//  WeiDuKeJi
//
//  Created by 谷银行 on 2019/1/26.
//  Copyright © 2019 谷银行. All rights reserved.
//

#import "DataManager.h"
#import "FMDB.h"


static DataManager*_defaulthandle =nil;

@interface DataManager ()

@property(nonatomic,strong)FMDatabase *fMDB;  //

@end

@implementation DataManager
+(DataManager*)sharedDataHandle

{
    
    if (_defaulthandle == nil) {
        
        _defaulthandle = [[DataManager alloc] init];
        
        
        
    }
    
    return _defaulthandle;
    
}

//+(instancetype)allocWithZone:(struct _NSZone*)zone
//
//{
//
//    if (_defaulthandle == nil) {
//
//        _defaulthandle= [super allocWithZone:zone];
//
//    }
//
//    return _defaulthandle;
//
//}

-(FMDatabase *)fMDB
{
    
    if(!_fMDB) {
        
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"movies.sqlite"];
        
        NSLog(@"path=====%@",path);
        
        _fMDB= [FMDatabase databaseWithPath:path];
        
        [self initTable];
        
    }
    
    return _fMDB;
    
}

// 初始化数据表

-(void)initTable

{
    
    [_fMDB open];
    
    [_fMDB executeUpdate:@"CREATE TABLE movie (id INTEGER PRIMARY KEY AUTOINCREMENT,nickName TEXT,phone TEXT, pwd TEXT,sessionId TEXT,userName TEXT,userId INT,whetherVip INT,whetherFaceId INT)"];
    
    [_fMDB close];
    
}
-(void)addOneMovie:(IDModel*)movie

{
    [self.fMDB open];
    
    [self.fMDB executeUpdateWithFormat:@"insert into movie (nickName,phone,pwd,sessionId,userName,userId,whetherVip,whetherFaceId) values (%@,%@,%@,%@,%@,%d,%d,%d)",movie.nickName,movie.phone,movie.pwd,movie.sessionId,movie.userName,movie.userId,movie.whetherVip,movie.whetherFaceId];
    NSLog(@"插入成功");
    
    [self.fMDB close];
    
}

//-(void)deleteMovieByID:(int)title
//
//{
//    [self.fMDB open];
//
//    [self.fMDB executeUpdateWithFormat:@"DELETE FROM movie WHERE id = %d",title];
//
//    [self.fMDB close];
//}

-(NSArray*)getAllMovies
{
    [self.fMDB open];
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    FMResultSet *result = [self.fMDB executeQuery:@"SELECT * FROM movie"];
    while([result next])
    {
        IDModel *movie = [[IDModel alloc]init];
        [arr addObject:movie];
        movie.ID= [result intForColumnIndex:0];
        
        movie.nickName = [result stringForColumnIndex:1];
        movie.phone = [result stringForColumnIndex:2];
        movie.pwd = [result stringForColumnIndex:3];
        movie.sessionId = [result stringForColumnIndex:4];
        movie.userName = [result stringForColumnIndex:5];
        movie.userId = [result intForColumnIndex:6];
        movie.whetherVip = [result intForColumnIndex:7];
        movie.whetherFaceId = [result intForColumnIndex:8];
    
    }
    
    [self.fMDB close];
    
    return[arr copy];
}
@end
